package com.cf.base.comm.base;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleRegistry;

import com.cf.base.mvp.mvp.IBaseView;
import com.cf.base.mvp.mvp.IPresenter;
import com.cf.base.mvp.mvp.proxy.ProxyImpl;
import com.cf.base.mvp.rx.LifecycleToRxSubject;
import com.zj.cf.fragments.BaseLinkageFragment;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import io.reactivex.subjects.BehaviorSubject;

/**
 * @author yangji
 */
public abstract class BaseLinkageMvpFragment<P extends IPresenter> extends BaseLinkageFragment implements IBaseView {

    private LifecycleToRxSubject subject = LifecycleToRxSubject.create();

    /**
     * 重写 Fragment 生命周期
     */
    private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

    @NonNull
    @Override
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }

    @Override
    public BehaviorSubject<Lifecycle.Event> getSubject() {
        return subject.getSubject();
    }

    private ProxyImpl<P> proxyPresenter;

    public P getPresenter() {
        return proxyPresenter.getMainPresenter();
    }


    @Override
    protected void onCreate() {
        super.onCreate();
        proxyPresenter = new ProxyImpl<P>() {
        };
        proxyPresenter.bindPresenter(this);
        getLifecycle().addObserver(subject);
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
    }


    @Override
    protected void onStarted() {
        super.onStarted();
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
    }

    @Override
    protected void onReStart() {
        super.onReStart();
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
    }

    @Override
    protected void onResumed() {
        super.onResumed();
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
    }

    @Override
    protected void onPaused() {
        super.onPaused();
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);
    }

    @Override
    protected void onStopped() {
        super.onStopped();
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);
        if (proxyPresenter != null) {
            proxyPresenter.unBindPresenter();
        }
    }

    /**
     * 获取当前Fragment view
     *
     * @param layoutInflater inflater
     * @param viewGroup      rootView
     * @return 当前layout View
     */
    @NotNull
    @Override
    protected abstract View getView(@NotNull LayoutInflater layoutInflater, @Nullable ViewGroup viewGroup);

}
